package com.jack.helloworld.adapter;

import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.jack.helloworld.R;
import com.jack.helloworld.bean.Recorder;
import com.jack.helloworld.util.ScreenUtil;

import java.util.List;

/**
 * Created by xiaofeng on 2017/4/25.
 */

public class AudioRecorderAdapter extends ArrayAdapter<Recorder> {

    private static final String AUDIO_RECORDER_TIME_SUFFIX = "\"";
    private static final float MIN_ITEM_WIDTH_PERCENT = 0.15f;
    private static final float MAX_ITEM_WIDTH_PERCENT = 0.7f;
    private int mMinItemWidth;
    private int mMaxItemWidth;
    private LayoutInflater mInflater;

    public AudioRecorderAdapter(Context context, List<Recorder> datas) {
        super(context, -1, datas);
        mInflater = LayoutInflater.from(getContext());
        mMinItemWidth = (int) (ScreenUtil.getWindowsWidth((Activity) context) * MIN_ITEM_WIDTH_PERCENT);
        mMaxItemWidth = (int) (ScreenUtil.getWindowsWidth((Activity) context) * MAX_ITEM_WIDTH_PERCENT);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;
        if (viewHolder == null) {
            viewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_list_recorder, parent , false);
            viewHolder.audioRecorderTime = (TextView) convertView.findViewById(R.id.tv_audio_recorder_time);
            viewHolder.audioRecorderLength = convertView.findViewById(R.id.fl_audio_recorder_length);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.audioRecorderTime.setText(Math.round(getItem(position).getTime()) + AUDIO_RECORDER_TIME_SUFFIX);
        ViewGroup.LayoutParams layoutParams = viewHolder.audioRecorderLength.getLayoutParams();
        layoutParams.width = (int) (mMinItemWidth + getItem(position).getTime() / 60f * mMaxItemWidth);

        return convertView;
    }

    private class ViewHolder {
        TextView audioRecorderTime;
        View audioRecorderLength;
    }
}
